// Fill out your copyright notice in the Description page of Project Settings.


#include "AI/BTService_FindNearestPlayer.h"

#include "AIController.h"
#include "BehaviorTree/BTFunctionLibrary.h"
#include "Kismet/GameplayStatics.h"

void UBTService_FindNearestPlayer::TickNode(UBehaviorTreeComponent& OwnerComp, uint8* NodeMemory, float DeltaSeconds)
{
	Super::TickNode(OwnerComp, NodeMemory, DeltaSeconds);

	// 获取AI控制器控制的Pawn
	const APawn* OwingPawn = AIOwner->GetPawn();

	// 获取与Pawn相反的标签
	const FName TargetTag = OwingPawn->ActorHasTag(FName("Player")) ? FName("Enemy") : FName("Player");

	// 获取所有与目标标签相同的Actor
	TArray<AActor*> ActorsWithTag;
	UGameplayStatics::GetAllActorsWithTag(OwingPawn, TargetTag, ActorsWithTag);

	float ClosestDistance = TNumericLimits<float>::Max(); // 浮点数的最大值
	AActor* ClosestActor = nullptr;
	// 遍历获取最近的目标
	for (AActor* Actor : ActorsWithTag)
	{
		const float DistanceToTarget = OwingPawn->GetDistanceTo(Actor);
		if (DistanceToTarget < ClosestDistance)
		{
			ClosestDistance = DistanceToTarget;
			ClosestActor = Actor;
		}
	}
	// 设置黑板键对应的值为对象
	UBTFunctionLibrary::SetBlackboardValueAsObject(this, NearestTargetKey, ClosestActor);
	UBTFunctionLibrary::SetBlackboardValueAsFloat(this, NearestTargetDistanceKey, ClosestDistance);
}
